<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model;

use buwang\base\BaseModel;
use buwang\traits\ModelTrait;
use think\facade\Cache;
use buwang\facade\WechatPay;
use app\manage\model\User;
use buwang\base\TimeModel;

class UserRecharge extends TimeModel
{

    use ModelTrait;

    protected $pk = 'id';

    protected $deleteTime = false;


    public function user()
    {
        return $this->belongsTo('\app\common\model\User', 'uid', 'id');
    }


    public function getUserList($memberId = 0)
    {
        $self = new User;
        if ($memberId) {
            $ids = MemberMiniapp::where('member_id', $memberId)->column('id');
            if ($ids) {
                $self = $self->where('member_miniapp_id', 'in', $ids);
            }
        }
        return $self->column('nickname', 'id');
    }

    public function getRechargeTypeList()
    {
        return ['mini_program' => '小程序充值','official' => '公众号充值',];
    }

    public function getPaidList()
    {
        return ['0' => '未充值', '1' => '已充值',];
    }


    /**创建充值单
     * @param $that  当前控制器
     * @param $uid  用户id
     * @param $selectId  套餐id
     * @param $price  套餐id为0时，自定义充值金额
     * @param $type  支付方式：mini_program 微信小程序支付
     * @param bool $trans
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createRecharge($uid, $selectId = 0, $price = 0, $type = 'mini_program', $app_id = 0, $trans = false)
    {
        $user = User::find($uid);
        if (!$user) return self::setError('充值用户不存在');
        //查询充值套餐
        if ($selectId == 0) {
            //1,套餐为0，输入金额
            $give = 0;//满赠金额
        } else {
            //2,有套餐
            $recharge = bw_data('recharge_select', $selectId);
            if (!$recharge) return self::setError('找不到该充值套餐');
            $price = $recharge['price'];//充值金额
            $give = $recharge['give'];//满赠金额
        }
        if ($price <= 0 || $give < 0) return self::setError('该充值套餐数值异常');
        if (!in_array($type, ['mini_program','official'])) return self::setError('无此支付类型');
        //创建充值单
        $order_sn = get_uuid();//生成充值单号
        $order_data = [
            'order_id' => $order_sn,
            'uid' => $uid,
            'price' => $price,
            'give_price' => $give,
            'recharge_type' => $type,
            'add_time' => time(),
            'paid' => 0,
        ];
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            $self = new self;
            $res1 = $self->save($order_data);
            switch ($type) {
                case "mini_program":
                    //去请求微信支付接口
                    $payparm = [
                        'openid' => $user['miniapp_uid'],
                        'miniapp_id' => $app_id,
                        'name' => '余额充值',
                        'order_no' => $order_sn,
                        'total_fee' => $price * 100,//分
                        'notify_url' => (string)url('api/notifyMini/' . $app_id, [], false, true),
                    ];
                    $ispay = WechatPay::orderPay($payparm);//不传支付方式trade_type默认为JSAPI支付
                    if ($ispay['code'] == 0) $res2 = false;
                    break;
                case "official":
                    //去请求微信支付接口
                    $payparm = [
                        'openid' => $user['official_uid'],
                        'miniapp_id' => $app_id,
                        'name' => '余额充值',
                        'order_no' => $order_sn,
                        'total_fee' => $price * 100,//分
                        'notify_url' => (string)url('api/notifyOfficial/' . $app_id, [], false, true),
                    ];
                    $ispay = WechatPay::orderPay($payparm,true);//不传支付方式trade_type默认为JSAPI支付
                    if ($ispay['code'] == 0) $res2 = false;
                    break;
                //...
            }


            $res = $res && $res1 && $res2 && true;

            if ($trans) {
                self::checkTrans($res);
            }
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            return self::setError($e->getMessage());
        }
        if (!$res1) return self::setError('创建充值单失败');
        if (!$res2) return self::setError($ispay['msg']);
        if (!$res) return self::setError('充值订单创建失败');
        switch ($type) {
            case "mini_program":
            case "official":
                $res = $ispay['data'];
                $res['timeStamp'] = $res['timestamp'];
                break;
            //...
        }
        return $res;
    }


    //充值完成回调
    public static function paySeccess($order_id, $price, $trans = false)
    {
        $order = self::where('order_id', $order_id)->where('price', $price)->find();
        if (!$order) return self::setError($order_id . '充值单不存在或已支付');
        //已支付过直接返回
        if ($order['paid'] == 1) return true;
        $user = User::find($order['uid']);
        if (!$user) return self::setError($order_id . '充值用户不存在');
        $price = $order['price'];//充值金额
        $give_price = $order['give_price'];//赠送金额
        //充值金额加赠送金额 = 总充值金额
        $price = bcadd($price, $give_price, 2);
        if ($trans) {
            self::startTrans();
        }
        $res = $res1 = $res2 = true;
        try {
            //加余额
            if ($price) {
                switch ($order['recharge_type']) {
                    case "mini_program":
                    case "official":
                        $info = "微信充值余额{$price}元,已到账";
                        if ($give_price > 0) $info = "微信充值余额{$price}(含套餐赠送余额{$give_price})元,已到账";
                        break;
                    default:
                        $info = "充值余额{$price}元,已到账";
                        if ($give_price > 0) $info = "充值余额{$price}(含套餐赠送余额{$give_price})元,已到账";
                }
                $res1 = User::changeMoney($order['uid'], $price, '充值余额', 'recharge', $info, $order['id']);
            }
            //更改充值单状态
            $order['paid'] = 1;
            $order['pay_time'] = time();
            $res2 = $order->save();
            $res = $res && $res1 && $res2 && true;
            if ($trans) {
                self::checkTrans($res);
            }
            event('UserRechargeSuccess',[$user,$order]);
        } catch (\Exception $e) {
            if ($trans) {
                self::rollback();
            }
            event('UserRechargeFail',[$user,$order,$e->getMessage()]);

            return self::setError($order_id . '充值失败,原因：' . $e->getMessage());
        }
        if (!$res){
            event('UserRechargeFail',[$user,$order,'充值失败,原因未知']);
            return self::setError($order_id . '充值失败');
        }

        return $res;
    }


    /**
     * 充值列表
     */
    public static function rechargeList($uid, $page = 1, $limit = 10, $sort = 'id desc')
    {

        $list = self::where('uid', '=', $uid)
            ->where('paid', 1)
            ->page($page, $limit)
            ->order($sort)
            ->select()->toArray();
        //累计充值金额
        $extract_total = UserBill::getRecharge($uid);
        return ['data' => $list, 'page' => $page, 'limit' => $limit, 'recharge_total' => $extract_total];

    }


    /**
     * 今日用户总充值
     */
//    public static function rechargeTotal($member_id){
//
//        $list = self::where('uid','=',$uid)
//            ->where('paid',1)
//            ->page($page, $limit)
//            ->order($sort)
//            ->select()->toArray();
//        //累计充值金额
//        $extract_total= UserBill::getRecharge($uid);
//        return ['data'=>$list,'page'=>$page,'limit'=>$limit,'recharge_total'=>$extract_total];
//
//    }


}